﻿using FastMvc.Auth;
using FastMvc.Models;
using JQ.SAAS.Entity;
using JQ.SAAS.IdentifyServer.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace JQ.SAAS.IdentifyServer.Controllers
{
    [Route("api")]
    [ApiController]
    public class LoginController
    {
        [HttpPost("login")]
        public BaseResult<UserAuthInfo> login([FromBody] LoginRequest LoginParam)
        {
            using (var db = FastMvc.DBHelper.SqlSugarDB)
            {
                sys_user user = null;

                #region 登录验证
                string token = "";
                if (!string.IsNullOrEmpty(LoginParam.LoginToken))
                {
                    user = db.Queryable<sys_user>()
                        .Where(t => t.LoginToken == LoginParam.LoginToken && t.TokenExpireTime > DateTime.Now)
                        .Single();
                    if(user!=null)
                        token = LoginParam.LoginToken;
                }
                else
                {
                    user = db.Queryable<sys_user>()
                        .Where(t => t.LoginName == LoginParam.UserName && t.Password == LoginParam.PassWord)
                        .Single();
                    if (user != null)
                        token = Guid.NewGuid().ToString();
                }

                if (user == null)
                {
                    return new BaseResult<UserAuthInfo>()
                    {
                        code = 1,
                        success = false,
                        message = "登录失败!"
                    };
                }
                #endregion

                #region 更新登录信息
                bool needUpdate = false;
                if (user.LoginToken != token)
                {
                    needUpdate = true;
                    user.LoginToken = token;
                }
                if (user.TokenExpireTime < DateTime.Now.AddHours(1))
                {
                    needUpdate = true;
                    user.TokenExpireTime = DateTime.Now.AddHours(2);
                }
                if (needUpdate)
                {
                    db.Updateable(user).ExecuteCommand();
                }
                #endregion


                var userOrg = db.Queryable<sys_organization>()
                    .Where(t => t.sId == user.sOrgId)
                    .First();

                var data = new UserAuthInfo()
                {
                    sUserId = user.sId,
                    sUserName = user.LoginName,
                    sOrgId = userOrg?.sId,
                    sOrgName = userOrg?.sOrgName,
                    LoginToken = token,
                    Claims = new Dictionary<string, string>()
                };
                if (userOrg != null)
                {

                    data.Claims.Add("Phone", userOrg.Phone);
                    data.Claims.Add("Email", userOrg.Email);
                    data.Claims.Add("DBConnection", userOrg.DBConnection);
                    data.Claims.Add("DBSlaveConnection", userOrg.DBSlaveConnection);
                }
                return new BaseResult<UserAuthInfo>()
                {
                    code = 0,
                    success = true,
                    message = "登录成功！",
                    data = data
                };
            }
        }

        [HttpPost("logout")]
        public BaseResult logout([FromBody] LogoutRequest LogoutParam)
        {
            using (var db = FastMvc.DBHelper.SqlSugarDB)
            {

                db.Updateable<sys_user>().SetColumns(t => t.LoginToken == "")
                    .Where(t => t.LoginToken == LogoutParam.Token)
                    .ExecuteCommand();
            }
            return BaseResult.Success("登出成功！");
        }
    }
}
